import datetime
import md5Converter
from flask import Flask, g, request
from tornado.database import Connection

def create_app():
    # create the flask application
    app = Flask(__name__)

    # Deploying with Fabric http://flask.pocoo.org/docs/patterns/fabric/
    app.url_map.converters['md5'] = md5Converter.md5Converter
    
    # add file logging handler
    import logging
    from logging.handlers import TimedRotatingFileHandler
    file_handler = TimedRotatingFileHandler('trace.log', 'midnight', 1)
    #file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    
    def gated(expires, max_age, content_type="text/javascript"):
        def decorator(f):
            from functools import update_wrapper 
            def gate_request(*args, **kwargs):
                resp = app.make_response(f(*args, **kwargs))
                resp.headers['Content-type'] = content_type
                resp.headers['Expires'] = expires
                resp.headers['Cache-Control'] = 'max-age=%s' % str(max_age)
                return resp
    
            return update_wrapper(gate_request, f)
        return decorator
    
    # NOTE: If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached.
    @app.route("/total/<int:partner_id>/", methods=['GET'])
    @gated(expires="+1h", max_age=3600)
    def total(partner_id):
        total = g.db.get("select count(*) from PartnerGate_db.PartnerGateLookup where partnerid=%s;", partner_id)
        return str(total['count(*)'])
    
    @app.route("/<int:partner_id>/<md5:url>", methods=['GET'], strict_slashes=False)
    @gated(expires="+7d", max_age=604800)
    def access(partner_id, url):
        dbresp = g.db.get("call sp_PartnerGateLookup(%s,%s);", url, partner_id)
        resp = str(dbresp.LastOccuranceTS)
        callback = request.args.get("callback")
        if callback:
            resp = "%s(%s);\n" % (callback, resp)
    
        return resp
    
    @app.errorhandler(404)
    def page_not_found(error):
        #app.logger.error(error)
        return "0"
        #return "0", 404
    
    @app.errorhandler(500)
    def default_error_handler(error):
        #app.logger.error(error)
        return "0"
        #return "0", 500
    
    @app.before_request
    def connect_db():
        g.db = Connection("localhost", "PartnerGate_db", "root", "root")
        #g.db =yy Connection(config.DB_HOST, config.DB_NAME, config.DB_USER, config.DB_PASSWD)
    
    @app.after_request
    def close_connection(response):
        g.db.close()
        return response

    return app
